package com.dkm.orproject.dkmoa.action.flow;

import com.alibaba.fastjson.JSONObject;
import com.dkm.orproject.dkmoa.domain.OaFlow;
import com.dkm.orproject.dkmoa.domain.OaFlowSchedule;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.flow.OaFlowScheduleService;
import com.dkm.orproject.dkmoa.service.flow.OaFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName : OaFlowAction  //类名
 * @Description : 流程管理Action  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-08-27 08:44  //时间
 */
@RestController
@RequestMapping("/OaFlowAction")
public class OaFlowAction {

    /**
     * 流程进度服务接口
     */
    @Resource
    OaFlowService flowService;

    @Resource
    OaFlowScheduleService flowScheduleService;

    /**
     * 工具类
     */
    @Resource
    Tools tools;

    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 分页查询
     * @param flow 流程进度模型 用于条件查询
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 当前页数
     * @param limit 显示的行数
     * @return 流程进度集
     */
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(OaFlow flow,
                                      String startTime,
                                      String endTime,
                                      Integer page,
                                      Integer limit,
                                      HttpServletRequest request){
        try{
            List<OaFlow> dataDictionaries=flowService.findAll(flow,startTime,endTime,page,limit);
            Long rowCount=flowService.rowCount(flow,startTime,endTime);
            return Tools.maps(dataDictionaries,rowCount);
        }catch (Exception e){
            addErrorLog(request,"流程进度分页查询",e);
        }
        return null;

    }

    /**
     * id查询
     * @param id 流程进度主键
     * @return 流程进度模型
     */
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaFlow findById(@PathVariable("id") Long id, HttpServletRequest request){
        try{
            return flowService.findById(id);
        }catch (Exception e){
            addErrorLog(request,"流程进度id查询",e);
        }
        return null;
    }

    /**
     * 关键字查询 主要用于下拉框查询
     * @param key 流程进度关键字
     * @return 流程进度集
     */
    @UserLoginToken
    @GetMapping("findKeyword/{key}")
    public List<OaFlow> findKeyword(@PathVariable("key") String key,HttpServletRequest request){
        try{
            return flowService.findKeyword(key);
        }catch (Exception e){
            addErrorLog(request,"流程进度关键字查询",e);
        }
        return null;
    }

    /**
     * 查询报错日志新增
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        e.printStackTrace();
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(e.getLocalizedMessage());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }

    /**
     * 新增或修改
     * @param flow 流程进度模型
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("addOrUpdate")
    public Map<String,Object> addOrUpdate(OaFlow flow,String select, HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            if(flow.getPkFlowId() !=null && flow.getPkFlowId()>0){
                row=flowService.update(flow,select,personnel.getPersonnelName());
                log.setLogTitle("流程进度修改");
            }else{
                row=flowService.add(flow,select,personnel.getPersonnelName());
                log.setLogTitle("流程进度新增");
            }
            log.setLogType("1");
            log.setLogBody(JSONObject.toJSON(flow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            log.setLogTitle("流程进度操作");
            log.setLogType("0");
            log.setLogBody(e.getLocalizedMessage());
            tools.errorMap(map,log);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 流程进度id集
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String,Object> deleteAll(@RequestParam(value = "ids[]",required = false) Long[] ids,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            List<Long> list= Arrays.asList(ids);
            List<OaFlow> dataDictionaries=flowService.selectAll(list);
            row=flowService.deleteAll(list);
            log.setLogTitle("流程进度批量删除");
            log.setLogBody(JSONObject.toJSON(dataDictionaries).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            log.setLogTitle("流程进度批量删除");
            log.setLogBody(e.getLocalizedMessage());
            log.setLogType("0");
            tools.errorMap(map,log);
        }
        return map;
    }

    /**
     * id删除
     * @param id 流程进度id
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable(value = "id",required = false)Long id,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            OaFlow flow=flowService.findById(id);
            row=flowService.deleteById(id);
            log.setLogTitle("流程进度删除");
            log.setLogBody(JSONObject.toJSON(flow).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            log.setLogBody(e.getLocalizedMessage());
            log.setLogTitle("流程进度删除");
            log.setLogType("0");
            tools.errorMap(map,log);
        }
        return map;
    }

    /**
     *
     * @param id 表单id
     * @param request 服务器请求
     * @return 流程记录集
     */
    @UserLoginToken
    @GetMapping("selectFlowSchedule/{id}")
    public List<OaFlowSchedule> selectFlowSchedule(@PathVariable("id") Long id,HttpServletRequest request){
        try{
            return flowScheduleService.selectFlowSchedule(id);
        }catch (Exception e){
            addErrorLog(request,"流程进度记录查询",e);
        }
        return null;
    }

    /**
     * 优化代码
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }
}
